package org.iridium.allcomments.buzz;

import org.iridium.allcomments.common.Constants;
import org.iridium.allcomments.dto.UserDTO;
import org.iridium.allcomments.exception.AllCommentsException;
import org.iridium.allcomments.persistance.UserInfoDAO;
import org.iridium.allcomments.persistance.UserInfoDAOImpl;

public class UserBuzz {

	/**
	 * write user info to table 'user_login' and 'user_login'
	 * 
	 * @param user
	 * @throws AllCommentsException
	 */
	public void register(UserDTO user) throws AllCommentsException {
		if (this.hasUser(user)) {
			throw new AllCommentsException("User already exists");
		}

		long userId = user.getUserId();
		UserInfoDAO dao = new UserInfoDAOImpl();
		dao.addItem(userId, user.getLoginName(), user.getPassword(), user
				.getEmail(), user.getNickname(), Constants.USER_ROLE_USERS);
	}

	/**
	 * a user to 'kill' hiself in AllComments
	 * 
	 * @param userId
	 */
	public void removeSelf(long userId) {
		UserInfoDAO dao = new UserInfoDAOImpl();
		dao.delItem(userId);
	}

	/**
	 * update password
	 * 
	 * @param userId
	 */
	public void updatePassword(UserDTO user) {
		UserInfoDAO mDao = new UserInfoDAOImpl();
		mDao.updatePassword(user.getUserId(), user.getPassword());
	}

	/**
	 * update user info TODO
	 * 
	 * @param user
	 */
	public void updateUserInfo(UserDTO user) {
		UserInfoDAO dao = new UserInfoDAOImpl();
		dao.updateItem(user.getUserId(), user.getNickname(),
				user.getRealName(), user.getSex(), user.getAge(), user
						.getLocation(), user.getQuestion(), user.getAnswer(),
				user.getMobile(), user.getEmail());
	}

	/**
	 * login system
	 * 
	 * @param userId
	 * @param password
	 * @return
	 * @throws AllCommentsException
	 */
	public boolean login(long userId, String password)
			throws AllCommentsException {
		UserInfoDAO dao = new UserInfoDAOImpl();

		if (!dao.existsUser(userId)) {
			throw new AllCommentsException("This user does not exist.");
		}

		if (!password.equals(dao.queryPassword(userId))) {
			throw new AllCommentsException("Password does not match.");
		}

		return true;
	}

	/**
	 * to query if there is an account of the user in this system already.
	 * 
	 * @param user
	 * @return
	 */
	public boolean hasUser(UserDTO user) {
		UserInfoDAO dao = new UserInfoDAOImpl();
		return dao.existsUser(user.getUserId());
	}
}
